package org.lql.algo.codecrush.hot100.hash;

import java.util.HashSet;
import java.util.Set;

/**
 * @author: liangqinglong
 * @date: 2025-09-16 18:06
 * @description: 128. 最长连续序列 <a href="https://leetcode.cn/problems/longest-consecutive-sequence/description/?envType=study-plan-v2&envId=top-100-liked">...</a>
 **/
public class LongestConsecutive {

	public int longestConsecutive(int[] nums) {
		// 边界判断
		if (nums == null || nums.length == 0) {
			return 0;
		}
		// 将元素放入set进行去重
		Set<Integer> numSet = new HashSet<>();
		for (int num : nums) {
			numSet.add(num);
		}
		int longestStreak = 0;
		for (Integer num : numSet) {
			if (!numSet.contains(num - 1)) {
				int currentNum = num;
				int currentStreak = 1;
				// 计算连续序列长度
				while (numSet.contains(currentNum + 1)) {
					currentNum++;
					currentStreak++;
				}
				// 更新最长连续序列的长度
				longestStreak = Math.max(longestStreak, currentStreak);
			}
		}
		return longestStreak;
	}

	public static void main(String[] args) {
		LongestConsecutive longestConsecutive = new LongestConsecutive();
		// 4
		System.out.println(longestConsecutive.longestConsecutive(new int[]{100, 4, 200, 1, 3, 2}));
		// 9
		System.out.println(longestConsecutive.longestConsecutive(new int[]{0, 3, 7, 2, 5, 8, 4, 6, 0, 1}));
		// 3
		System.out.println(longestConsecutive.longestConsecutive(new int[]{1, 2, 0, 1}));
	}
}
